<?php
class activeAction extends backendAction {

	public function _initialize() {
        parent::_initialize();
        $this->_mod = D('active');
    }

    public function export(){
        set_time_limit (0);
        ini_set('memory_limit', '2048M');
        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        date_default_timezone_set('PRC');

        import("PHPExcel", VENDOR_PATH . 'PHPExcel', '.php');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                     ->setLastModifiedBy("Maarten Balliauw")
                                     ->setTitle("Office 2007 XLSX Test Document")
                                     ->setSubject("Office 2007 XLSX Test Document")
                                     ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                     ->setKeywords("office 2007 openxml php")
                                     ->setCategory("Test result file");
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('15');
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth('40');
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth('30');
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth('40');
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth('15');

        // Add some data
        $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A1', 'id')
                    ->setCellValue('B1', '激活码')
                    ->setCellValue('C1', '创建时间')
                    ->setCellValue('D1', '失效时间')
                    ->setCellValue('E1', '状态');

        $list_sql = "SELECT * FROM `wxs_active` " ;
        $list = M()->query($list_sql);

        foreach ($list as $key => $item) {
            $item['status'] = ($item['status']==='1')?'激活':'未激活';

            $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A'.($key+2), ' '.$item['id'])
                        ->setCellValue('B'.($key+2), ' '.$item['code_num'])
                        ->setCellValue('C'.($key+2), ' '.date('Y-m-d H:i:s',$item['created']))
                        ->setCellValue('D'.($key+2), ' '.date('Y-m-d H:i:s',$item['expired']))
                        ->setCellValue('E'.($key+2), ' '.$item['status']);
        }


        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('Simple');


        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);


        // Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="激活码.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header ('Pragma: public'); // HTTP/1.0

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }


    public function index(){
		$p = ($_GET['p'])?$_GET['p']:1;
        $pageNum = 25;
        $index = ($p-1)*$pageNum;

		$status = $_GET['status'];     
		$expired = $_GET['expired'];
		$param = '';
		$where = ' where 1 ';    
		if ($status==='0') {
			$where .= '	and `status`=0 ';
			$param .= '&status=0';
		}elseif ($status==='1') {
			$where .= '	and `status`=1 ';
			$param .= '&status=1';
		}

		if ($expired==='1') {
			$where .= '	and `expired`<'.time();
			$param .= '&expired=1';
		}elseif ($expired==='0') {
			$where .= '	and `expired`>'.time();
			$param .= '&expired=0';
		}

        $list_sql = "SELECT * FROM `wxs_active` " .$where . " ORDER BY id DESC  LIMIT {$index},{$pageNum}";
        $list = M()->query($list_sql);


        $this->assign('list',$list); 
        import("ORG.Util.Page"); 
        
        $count_sql = "SELECT COUNT(id) total FROM `wxs_active` " .$where ;
        $count = M()->query($count_sql); 
        $count = $count[0]['total'];
        $Page = new Page($count,$pageNum,$param); 

        $show = $Page->show(); 
        $this->assign('list',$list); 
        $this->assign('page',$show);
        $this->assign('status',$status);
        $this->assign('expired',$expired);
        $this->display();
    }

    public function add(){
    	$this->display();
    }

    public function save(){
        $count = trim($_POST['count']);
    	$expired = trim($_POST['expired']);
    	if ($count<1) {
    		$this->error('请输入激活码数量');
    	}

        if (!$expired) {
            $this->error('请输入失效时间');
        }
    	
    	$this->_mod->startTrans();
    	$status = 1;
        
        $data['expired'] = strtotime($expired);
        // $data['expired'] = strtotime("+1 month");

    	for ($i=0; $i < $count; $i++) { 
    		$data['code_num'] = rand(1000,9999).substr( md5(uniqid(rand(0,99999999)))   ,8,16   );

	    	$data['created'] = time();
	    	$res = $this->_mod->add($data);
	    	if (!$res) {
	    		$status = 0;
	    	}
    	}

    	if ($status) {
    		$this->_mod->commit();
    		$this->success(L('operation_success'), U('index'));
    	}else{
    		$this->_mod->rollback();
    		$this->success(L('operation_failure'), U('index'));
    	}


    }

    public function use_list(){
 		$p = ($_GET['p'])?$_GET['p']:1;
        $pageNum = 25;
        $index = ($p-1)*$pageNum;

		    
		$expired = $_GET['expired'];
		$username = $_GET['username'];
		$car_no = $_GET['car_no'];
		$code_num = $_GET['code_num'];

		$param = '';
		$where = ' where 1 ';    
		
		if ($expired==='1') {
			$where .= '	and `expired`<'.time();
			$param .= '&expired=1';
		}elseif ($expired==='0') {
			$where .= '	and `expired`>'.time();
			$param .= '&expired=0';
		}

		if ($username) {
			$where .= "	and `username`= '{$username}'";
			$param .= '&username='.$username;
		}

		if ($car_no) {
			$where .= "	and `car_no`= '{$car_no}'";
			$param .= '&car_no='.$car_no;
		}

		if ($code_num) {
			$where .= "	and `code_num`= '{$code_num}'";
			$param .= '&code_num='.$code_num;
		}


        $list_sql = "SELECT * FROM `wxs_active_use`" .$where . " ORDER BY id DESC  LIMIT {$index},{$pageNum}";
        $list = M()->query($list_sql);


        $this->assign('list',$list); 
        import("ORG.Util.Page"); 
        
        $count_sql = "SELECT COUNT(id) total FROM `wxs_active_use` " .$where ;
        $count = M()->query($count_sql); 
        $count = $count[0]['total'];
        $Page = new Page($count,$pageNum,$param); 

        $show = $Page->show(); 
        $this->assign('list',$list); 
        $this->assign('page',$show);
        $this->assign('expired',$expired);
        $this->assign('code_num',$code_num);
        $this->assign('car_no',$car_no);
        $this->assign('username',$username);
        $this->display();
    }


    public function car_type_list(){
        $p = ($_GET['p'])?$_GET['p']:0;
        session('callback_url','http://'.$_SERVER['HTTP_HOST'].'/index.php?g=admin&m=active&a=car_type_list&menuid=328&p='.$p);

        $M = M('active_type');
        $list = $M->order('id desc')->page($p.',25')->select();
        $this->assign('list',$list); // 赋值数据集
        import("ORG.Util.Page"); // 导入分页类
        $count = $M->count(); // 查诟满足要求癿总记录数
        $Page = new Page($count,25); // 实例化分页类 传入总记录数和每页显示癿记录数
        $show = $Page->show(); // 分页显示输出
        $this->assign('page',$show); // 赋值分页输出
        $this->display(); // 输出模板
    }

    public function add_car_type(){
        $this->display();
    }

    public function save_car_type(){
        $data['car_type'] = trim($_POST['car_type']);
        if ( !$data['car_type'] ) {
            $this->error('请输入车型');
        }
        $data['created'] = time();
        $M = M('active_type');

        $item = $M->where(array('car_type'=>$data['car_type'] ))->find();
        if (!empty( $item)) {
           $this->error('已添加过该车型,无需重复添加');
        }

        $res = $M->add($data);
        $this->success(L('operation_success'), U('car_type_list'));
    }

     public function edit_car_type(){
        $M = M("active_type");
        $id = $_GET['id'];
        $item = $M->where(array('id'=>$id))->find();
        $this->assign('item',$item); 
        $this->display(); 
    }

    public function update_car_type(){
        $M = M("active_type");
        $id=$_POST['id'];
        $data['car_type'] = trim($_POST['car_type']);
        
        $ref = $M->where(array('id'=>$id))->save($data);
        if($ref)
            header('Location:'.session('callback_url'));
        else
            $this->error(L('operation_failure'));
    }

    public function del_car_type(){
        $M = M("active_type"); // 实例化 User 对象
        $res = $M->where('id='.(int)$_GET['id'] )->delete(); 
        header('Location:'.session('callback_url'));
    }
}